#include "mutable_buffer.h"

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <esp_log.h>

struct mutable_buffer
{
    char *buf;
    size_t size;
};

mutable_buffer_t *mutable_buffer_create()
{
    mutable_buffer_t *mutable_buffer = (mutable_buffer_t *)malloc(sizeof(mutable_buffer_t));
    assert(mutable_buffer);
    memset(mutable_buffer, 0, sizeof(mutable_buffer_t));
    return mutable_buffer;
}

void mutable_buffer_free(mutable_buffer_t *mutable_buffer)
{
    if (mutable_buffer->buf)
    {
        free(mutable_buffer->buf);
    }
    free(mutable_buffer);
}

void mutable_buffer_append(mutable_buffer_t *mutable_buffer, const void *data, size_t size)
{
    assert(mutable_buffer);
    char* buf = realloc(mutable_buffer->buf, mutable_buffer->size + size + 1);
    assert(buf);
    memcpy(buf + mutable_buffer->size, data, size);
    mutable_buffer->size += size;
    buf[mutable_buffer->size] = 0;
    mutable_buffer->buf = buf;
}

char *mutable_buffer_get_buffer(mutable_buffer_t *mutable_buffer)
{
    return mutable_buffer->buf;
}
